package compendiumAid.application.loadElementsList
{
	import compendiumAid.domain.ApplicationCursorManager;
	import compendiumAid.domain.ElementUtil;
	import compendiumAid.domain.vo.ElementVO;
	import compendiumAid.presentation.compendiumElements.CompendiumElementsPM;
	
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.controls.Alert;
	import mx.rpc.AsyncToken;
	import mx.rpc.http.HTTPService;
	import mx.utils.ObjectUtil;

	public class LoadElementsListCommand
	{
		private var service:HTTPService;
		
		[Inject]
		public var compendiumElementsPM:CompendiumElementsPM;
		
		[Init]
		public function init():void
		{
			service = new HTTPService();
		}
		
		[Command]
		public function load(event:LoadElementsListEvent):AsyncToken
		{
			service.url = "http://www.wizards.com/dndinsider/compendium/CompendiumSearch.asmx/ViewAll?tab=" + event.classification + "&amp;NameOnly=false";
			
			ApplicationCursorManager.setBusyCursor();
			
			return service.send();
		}
		
		[CommandResult]
		public function onLoadResult(result:Object, event:LoadElementsListEvent):void
		{
			if (result != null)
			{
				event.elements.removeAll();
				
				for each (var elementObject:Object in result.Data.Results[event.classification])
				{
					var elementVO:ElementVO = ElementUtil.compendiumObjectToElementVO(elementObject, event.classification);
					
					event.elements.addItem(elementVO);
				}
				
				compendiumElementsPM.elements = ObjectUtil.copy(event.elements) as ArrayCollection;
				
				sortElements(compendiumElementsPM.elements);
			}
			
			ApplicationCursorManager.removeBusyCursor();
		}
		
		[CommandFault]
		public function onLoadFault(result:Object, event:LoadElementsListEvent):void
		{
			ApplicationCursorManager.removeBusyCursor();
			
			Alert.show("Load of elements " + event.classification + " failed.", "Error");
		}
		
		private function sortElements(elements:ArrayCollection):void
		{	
			var dataSortField:SortField = new SortField();
			dataSortField.name = "name";
			
			var dataSort:Sort = new Sort();
			dataSort.fields = [dataSortField];
			
			elements.sort = dataSort;
			elements.refresh();
		}
	}
}